"""
作者：Leagolas
日期：2023年12月20日
"""


import pandas as pd
from sklearn.decomposition import PCA
import numpy as np
from sklearn.linear_model import LinearRegression
import data_processor
import scipy
import statsmodels.api as sm
from statsmodels.tsa.arima.model import ARIMA
import statsmodels
import warnings
pd.options.mode.chained_assignment = None


# 指标
factors1_name = ['动量_15', '动量_1M', '动量_3M']
factors2_name = ['日均换手率_5', '乖离率_5', '标准差_5', '标准差乖离率_10']
factors12_name = ['动量_15', '动量_1M', '动量_3M', '日均换手率_5', '乖离率_5', '标准差_5', '标准差乖离率_10']



def get_statistics(select_factors, com_df, span = 0, isascending = True):
    FF3 = pd.read_csv("./cleaned_data/FF3_00.csv", dtype={"Code": str})
    FF3 = FF3.set_index("交易日期")
    Risk_Free = pd.read_csv("./cleaned_data/Risk_Free.csv", dtype={"Code": str})
    Risk_Free = Risk_Free.set_index("统计日期")
    result1_df = pd.DataFrame()
    result2_df = pd.DataFrame()
    for factor in select_factors:
        select = pd.DataFrame()

        for day in com_df["交易日期"].unique():
            s_df = com_df[com_df["交易日期"] == day]
            s_df = s_df.sort_values(factor, ascending=isascending)
            # s_df["十等分组区间"] = pd.qcut(s_df[factor], 10, duplicates='drop')
            s_df["十等分组区间"] = pd.qcut(s_df[factor], 10)
            # s_df.to_excel(r"C:\Users\19742\Desktop\得分详情.xlsx", index=True)
            # stop = input("暂停")

            split_dict = {}
            split_dict["交易日期"] = day
            for i in range(0, len(s_df["十等分组区间"].unique())):

                split_dict[str(i + 1)] = s_df[s_df["十等分组区间"] == s_df["十等分组区间"].unique()[i]][
                    "选股回测日收益率"].mean()

            # print(pd.DataFrame(data=split_dict, index=[0]))
            select = select._append(pd.DataFrame(data=split_dict, index=[factor]))



        select["Spread"] = select["10"] - select["1"]
        if (span > 0):
            select.to_csv(r"C:\Users\19742\Desktop\{}收益率.csv".format(str(span) + "期" + factor), index=True)
        elif (span == 0):
            select.to_csv(r"C:\Users\19742\Desktop\{}收益率.csv".format(factor), index=True)
        select = select.set_index("交易日期")
        select["市场风险溢价因子"] = FF3["市场风险溢价因子(流通市值加权)"]
        select["市值因子"] = FF3["市值因子(流通市值加权)"]
        select["账面市值比因子"] = FF3["账面市值比因子(流通市值加权)"]
        select["无风险利率"] = Risk_Free["无风险利率"]
        # select.to_excel(r"C:\Users\19742\Desktop\qcut.xlsx", index = True)
        # inputs = input("暂停")
        # print(select.columns)
        result1_dict = { }
        result2_dict = { }
        for i in range(0, 10):
            result1_dict[str(i + 1)] = select[str(i + 1)].mean()
            X = select[["市场风险溢价因子", "市值因子", "账面市值比因子"]]

            X = sm.add_constant(X)
            y = select[str(i + 1)] - select["无风险利率"]
            ols_model = sm.OLS(y, X)
            results = ols_model.fit()
            result2_dict[str(i + 1)] = results.params["const"]


        result1_dict["Spread"] = select["Spread"].mean()
        result1_dict["t(spread)"] = scipy.stats.ttest_1samp(select["Spread"], 0)[0]

        X = select[["市场风险溢价因子", "市值因子", "账面市值比因子"]]
        X = sm.add_constant(X)
        y = select["Spread"] - select["无风险利率"]
        ols_model = sm.OLS(y, X)
        results = ols_model.fit()
        result2_dict["Spread"] = results.params["const"]
        result2_dict["t(spread)"] = results.tvalues["const"]

        # print(pd.DataFrame(data=display_dict,index=[factor]))
        if (span > 0):
            result1_df = result1_df._append(pd.DataFrame(data=result1_dict,index=[str(span) + "期" + factor]))
            result2_df = result2_df._append(pd.DataFrame(data=result2_dict,index=[str(span) + "期" + factor]))
        elif (span == 0):
            result1_df = result1_df._append(pd.DataFrame(data=result1_dict, index=[factor]))
            result2_df = result2_df._append(pd.DataFrame(data=result2_dict, index=[factor]))
    return [result1_df, result2_df]

def get_result_SF7(all_Next):
    # all_next: 所有股票的面板数据，选股回测日收益率

    # 记录各期每只股票的得分
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)
    date_count = len(date_list)

    for day in range(date_count - 130, date_count):
        com_df = com_df._append(all_Next[all_Next["交易日期"] == date_list[day]])
        # print(day + 1)


    select_factors = ['动量_15', '动量_1M', '动量_3M', '日均换手率_5', '乖离率_5', '标准差_5', '标准差乖离率_10']
    result_df = get_statistics(select_factors, com_df, isascending = False)
    return result_df

def get_result_EqualWeight7(all_Next):
    # all_next: 所有股票的面板数据，选股回测日收益率

    # 记录各期每只股票的得分
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)
    date_count = len(date_list)

    for day in range(date_count - 130, date_count):
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]
        split_com["月收益率"] = curr["月收益率"]
        split_com["七因子等权重合成"] = all_Next[all_Next["交易日期"] == date_list[day]][factors12_name].sum(axis = 1)
        com_df = com_df._append(split_com)

    select_factors = ["七因子等权重合成"]
    result_df = get_statistics(select_factors, com_df, isascending = False)
    return result_df

def get_result_PCA7(all_Next, span):
    # all_next: 所有股票的面板数据，选股回测日收益率

    # 记录各期每只股票的得分
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)
    date_count = len(date_list)

    for day in range(date_count - 130, date_count):
        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]

        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]
        split_com["月收益率"] = curr["月收益率"]

        pca = PCA(n_components=1)
        pca.fit(np.array(s_df[factors12_name].values))
        weight = pca.components_[0]
        split_com["七因子主成分合成"] = np.dot(curr[factors12_name].values, weight)
        com_df = com_df._append(split_com)

    result_df = get_statistics(["七因子主成分合成"],  com_df, span= span, isascending = False)
    return result_df

def get_result_MaxIC7(all_Next, span):
    # all_next: 所有股票的面板数据，选股回测日收益率

    # 记录各期每只股票的得分
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)
    date_count = len(date_list)

    for day in range(date_count - 130, date_count):
        # print(date_list[day])
        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]

        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]
        factors_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()
        factors_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()
        # 计算最优化权重
        V_cov = curr[factors1_name].cov()
        weight_P = np.linalg.inv(V_cov) @ factors_P_IC[factors1_name].mean()
        weight_S = np.linalg.inv(V_cov) @ factors_S_IC[factors1_name].mean()
        split_com["因子最大化P_IC加权"] = np.dot(curr[factors1_name].values, weight_P)
        split_com["因子最大化S_IC加权"] = np.dot(curr[factors1_name].values, weight_S)
        split_com[["因子最大化P_IC加权", "因子最大化S_IC加权"]] = data_processor.truncate(
            split_com[["因子最大化P_IC加权", "因子最大化S_IC加权"]])
        split_com[["因子最大化P_IC加权", "因子最大化S_IC加权"]] = data_processor.standardize(
            split_com[["因子最大化P_IC加权", "因子最大化S_IC加权"]])

        com_df = com_df._append(split_com)

    select_factors = ["因子最大化P_IC加权", "因子最大化S_IC加权"]
    result_df = get_statistics(select_factors, com_df, span=span)
    return result_df

def get_result_MaxICIR7(all_Next, span):
    # all_next: 所有股票的面板数据，选股回测日收益率

    # 记录各期每只股票的得分
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)
    date_count = len(date_list)

    for day in range(date_count - 130, date_count):
        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]

        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]


        # 计算历史每期IC及Rank_IC, Sgima为因子IC的协方差矩阵
        factors12_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors12_name]

        Sigma12_P = factors12_P_IC[factors12_name].cov()
        weight12_P = np.linalg.inv(Sigma12_P) @ factors12_P_IC[factors12_name].mean()

        factors12_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors12_name]
        Sigma12_S = factors12_S_IC[factors12_name].cov()
        weight12_S =  np.linalg.inv(Sigma12_S) @ factors12_S_IC[factors12_name].mean()



        # 记录加权因子得分
        split_com["因子最大化P_ICIR加权"] = np.dot(curr[factors12_name].values, weight12_P)
        split_com["因子最大化S_ICIR加权"] = np.dot(curr[factors12_name].values, weight12_S)
        split_com[["因子最大化P_ICIR加权", "因子最大化S_ICIR加权"]] = data_processor.truncate(
            split_com[["因子最大化P_ICIR加权", "因子最大化S_ICIR加权"]])
        split_com[["因子最大化P_ICIR加权", "因子最大化S_ICIR加权"]] = data_processor.standardize(
            split_com[["因子最大化P_ICIR加权", "因子最大化S_ICIR加权"]])



        com_df = com_df._append(split_com)

    select_factors = ['因子最大化P_ICIR加权', '因子最大化S_ICIR加权']
    result_df = get_statistics(select_factors, com_df, span=span)
    return result_df

def get_result_MeanIC7(all_Next, span):
    # all_next: 所有股票的面板数据，选股回测日收益率

    # 记录各期每只股票的得分
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)
    date_count = len(date_list)

    for day in range(date_count - 130, date_count):
        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]

        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]

        # 计算历史每期IC及Rank_IC, Sgima为因子IC的协方差矩阵
        factors12_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors12_name]
        weight12_P = factors12_P_IC[factors12_name].mean()



        factors12_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors12_name]
        weight12_S = factors12_S_IC[factors12_name].mean()



        # 记录加权因子得分
        split_com["因子平均P_IC加权"] = np.dot(curr[factors12_name].values, weight12_P)
        split_com["因子平均S_IC加权"] = np.dot(curr[factors12_name].values, weight12_S)
        split_com[["因子平均P_IC加权", "因子平均S_IC加权"]] = data_processor.truncate(
            split_com[["因子平均P_IC加权", "因子平均S_IC加权"]])
        split_com[["因子平均P_IC加权", "因子平均S_IC加权"]] = data_processor.standardize(
            split_com[["因子平均P_IC加权", "因子平均S_IC加权"]])

        com_df = com_df._append(split_com)

    select_factors = ['因子平均P_IC加权', '因子平均S_IC加权']
    result_df = get_statistics(select_factors, com_df, span=span)
    return result_df

def get_result_HalfIC7(all_Next, span, half):
    # all_next: 所有股票的面板数据，选股回测日收益率

    # 记录各期每只股票的得分
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)
    date_count = len(date_list)

    for day in range(date_count - 130, date_count):
        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]

        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]


        seq = []
        for i in range(0, span):
            a = (i + 1 - span - 1) / half
            a = pow(2, a)
            seq.append(a)
        seq_dict = {"期数距离": seq}
        seq_df = pd.DataFrame(data= seq_dict)

        # 计算历史每期IC及Rank_IC, Sgima为因子IC的协方差矩阵
        factors12_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors12_name]

        #计算半衰加权后历史各期IC
        past_df = pd.DataFrame()
        for factor in factors12_name:
            past_df[factor] = factors12_P_IC[factor].mul(seq_df["期数距离"])
        weight12_P = past_df[factors12_name].mean()



        # 计算历史每期IC及Rank_IC, Sgima为因子IC的协方差矩阵
        factors12_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors12_name]

        #计算半衰加权后历史各期IC
        past_df = pd.DataFrame()
        for factor in factors12_name:
            past_df[factor] = factors12_S_IC[factor].mul(seq_df["期数距离"])
        weight12_S = past_df[factors12_name].mean()


        factors12_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors12_name]
        # 计算半衰加权后历史各期IC
        past_df = pd.DataFrame()
        for factor in factors12_name:
            past_df[factor] = factors12_P_IC[factor].mul(seq_df["期数距离"])
        weight12_P = past_df[factors12_name].mean()

        factors12_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors12_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors12_name]
        #计算半衰加权后历史各期IC
        past_df = pd.DataFrame()
        for factor in factors12_name:
            past_df[factor] = factors12_S_IC[factor].mul(seq_df["期数距离"])
        weight12_S = past_df[factors12_name].mean()

        # 记录加权因子得分
        split_com["因子半衰P_IC加权"] = np.dot(curr[factors12_name].values, weight12_P)
        split_com["因子半衰S_IC加权"] = np.dot(curr[factors12_name].values, weight12_S)
        split_com[["因子半衰P_IC加权", "因子半衰S_IC加权"]] = data_processor.truncate(
            split_com[["因子半衰P_IC加权", "因子半衰S_IC加权"]])
        split_com[["因子半衰P_IC加权", "因子半衰S_IC加权"]] = data_processor.standardize(
            split_com[["因子半衰P_IC加权", "因子半衰S_IC加权"]])

        com_df = com_df._append(split_com)

    select_factors = ['因子半衰P_IC加权', '因子半衰S_IC加权']
    result_df = get_statistics(select_factors, com_df, span = span)
    return result_df








# def get_result_PCA(all_Next, span):
#     # all_next: 所有股票的面板数据，选股回测日收益率
#
#     # 记录各期每只股票的得分
#     com_df = pd.DataFrame()
#
#     # all_next的时间范围
#     date_pd = all_Next["交易日期"].unique()
#     date_pd.sort()
#     date_list = list(date_pd)
#     date_count = len(date_list)
#
#     for day in range(date_count - 130, date_count):
#
#         # 历史数据
#         s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]
#
#
#         # 选股当天的指标数据
#         curr = all_Next[all_Next["交易日期"] == date_list[day]]
#
#         # 记录当天的选股得分依据
#         split_com = pd.DataFrame()
#         split_com = pd.DataFrame()
#         split_com["交易日期"] = curr["交易日期"]
#         split_com["证券代码"] = curr["证券代码"]
#         split_com["选股回测日收益率"] = curr["选股回测日收益率"]
#         split_com["月收益率"] = curr["月收益率"]
#
#
#         '''--------------主成分法进行同类因子合成------------------'''
#         # 因子1第一主成分
#         pca = PCA(n_components=1)
#         pca.fit(np.array(s_df[factors1_name].values))
#         weight1 = pca.components_[0]
#         s_df["因子1主成分合成"] = np.dot(s_df[factors1_name].values, weight1)
#         split_com["因子1主成分合成"] = np.dot(curr[factors1_name].values, weight1)
#
#         # 因子2第一主成分
#         pca = PCA(n_components=1)
#         pca.fit(np.array(s_df[factors2_name].values))
#         weight2 = pca.components_[0]
#         s_df["因子2主成分合成"] = np.dot(s_df[factors2_name].values, weight2)
#         split_com["因子2主成分合成"] = np.dot(curr[factors2_name].values, weight2)
#
#
#
#         # 主成分得分数据处理
#         s_df[["因子1主成分合成", "因子2主成分合成"]] =data_processor.truncate(
#             s_df[["因子1主成分合成", "因子2主成分合成"]])
#         s_df[["因子1主成分合成", "因子2主成分合成"]] = data_processor.standardize(
#             s_df[["因子1主成分合成", "因子2主成分合成"]])
#
#         split_com[["因子1主成分合成", "因子2主成分合成"]] =data_processor.truncate(
#             split_com[["因子1主成分合成", "因子2主成分合成"]])
#         split_com[["因子1主成分合成", "因子2主成分合成"]] = data_processor.standardize(
#             split_com[["因子1主成分合成", "因子2主成分合成"]])
#
#         para_dict = {"intercept":[],"w1":[],"w2":[]}
#
#         for day in s_df["交易日期"].unique():
#             ols = LinearRegression()
#             b_df = s_df[s_df["交易日期"] == day]
#             b_df[["因子1主成分合成", "因子2主成分合成"]] = data_processor.truncate(
#                 b_df[["因子1主成分合成", "因子2主成分合成"]])
#             b_df[["因子1主成分合成", "因子2主成分合成"]] = data_processor.standardize(
#                 b_df[["因子1主成分合成", "因子2主成分合成"]])
#             ols.fit(b_df[["因子1主成分合成", "因子2主成分合成"]], b_df["选股回测日收益率"])
#             para_dict["intercept"].append(ols.intercept_)
#             para_dict["w1"].append(ols.coef_[0])
#             para_dict["w2"].append(ols.coef_[1])
#
#         para_df = pd.DataFrame(data=para_dict)
#
#
#
#         "----------------------------------------------------------------------"
#         historical_coefs = np.array(para_df)
#         para_dict = {"intercept": [], "w1": [], "w2": []}
#         # 对每个系数进行ARIMA(1,0,1)预测
#         for i in range(3):  # 分别对intercept, w1, w2进行预测
#             model = ARIMA(historical_coefs[:, i], order=(1, 0, 1))
#             model_fit = model.fit(method_kwargs={"maxiter": 500})
#             # 预测下一个值
#             forecast = model_fit.forecast()[0]
#             para_dict["intercept" if i == 0 else f"w{i}"].append(forecast)
#
#         para_df = pd.DataFrame(data=para_dict)
#         "----------------------------------------------------------------------"
#
#
#         # 取平均
#         para_df = para_df.mean(axis=0)
#         # print(para_df)
#         split_com["主成分法ols综合得分"] = np.dot(split_com[["因子1主成分合成","因子2主成分合成"]],para_df[["w1","w2"]]) + para_df["intercept"]
#
#         # split_com["主成分法ols综合得分"] = np.dot(split_com[["因子1主成分合成","因子2主成分合成"]],para_df.loc[0,:][["w1","w2"]]) + para_df.loc[0,:]["intercept"]
#
#         com_df = com_df._append(split_com)
#
#     # com_df.to_excel(r"C:\Users\19742\Desktop\打分详情.xlsx", index=True)
#
#     select_factors = ['因子1主成分合成', '因子2主成分合成','主成分法ols综合得分']
#     result_df = get_statistics(select_factors, com_df, isascending = False, span= span)
#     return result_df




def get_result_PCA(all_Next, span):
    # all_next: 所有股票的面板数据，选股回测日收益率

    # 记录各期每只股票的得分
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)
    date_count = len(date_list)

    for day in range(date_count - 130, date_count):

        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]


        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]
        split_com["月收益率"] = curr["月收益率"]


        '''--------------主成分法进行同类因子合成------------------'''
        # 因子1第一主成分
        pca = PCA(n_components=1)
        pca.fit(np.array(s_df[factors1_name].values))
        weight1 = pca.components_[0]
        s_df["因子1主成分合成"] = np.dot(s_df[factors1_name].values, weight1)
        split_com["因子1主成分合成"] = np.dot(curr[factors1_name].values, weight1)

        # 因子2第一主成分
        pca = PCA(n_components=1)
        pca.fit(np.array(s_df[factors2_name].values))
        weight2 = pca.components_[0]
        s_df["因子2主成分合成"] = np.dot(s_df[factors2_name].values, weight2)
        split_com["因子2主成分合成"] = np.dot(curr[factors2_name].values, weight2)



        # # 主成分得分数据处理
        # split_com[["因子1主成分合成", "因子2主成分合成"]] =data_processor.truncate(
        #     split_com[["因子1主成分合成", "因子2主成分合成"]])
        # split_com[["因子1主成分合成", "因子2主成分合成"]] = data_processor.standardize(
        #     split_com[["因子1主成分合成", "因子2主成分合成"]])

        para_dict = {"intercept":[],"w1":[],"w2":[]}

        for day in s_df["交易日期"].unique():
            ols = LinearRegression()
            b_df = s_df[s_df["交易日期"] == day]
            ols.fit(b_df[["因子1主成分合成", "因子2主成分合成"]], b_df["选股回测日收益率"])
            para_dict["intercept"].append(ols.intercept_)
            para_dict["w1"].append(ols.coef_[0])
            para_dict["w2"].append(ols.coef_[1])

        para_df = pd.DataFrame(data=para_dict)
        historical_coefs = np.array(para_df)
        para_dict = {"intercept": [], "w1": [], "w2": []}
        # 对每个系数进行ARIMA(1,0,1)预测
        for i in range(3):  # 分别对intercept, w1, w2进行预测
            model = ARIMA(historical_coefs[:, i], order=(1, 0, 1))
            model_fit = model.fit(method_kwargs={"maxiter": 500})
            # 预测下一个值
            forecast = model_fit.forecast()[0]
            para_dict["intercept" if i == 0 else f"w{i}"].append(forecast)

        para_df = pd.DataFrame(data=para_dict)
        # 取平均
        # para_df = para_df.mean(axis=0)

        split_com["主成分法ols综合得分"] = np.dot(split_com[["因子1主成分合成","因子2主成分合成"]],para_df.loc[0,:][["w1","w2"]]) + para_df.loc[0,:]["intercept"]

        com_df = com_df._append(split_com)

    select_factors = ['因子1主成分合成', '因子2主成分合成','主成分法ols综合得分']
    result_df = get_statistics(select_factors, com_df, isascending = False, span = span)
    return result_df




def get_result_MaxIC(all_Next, span):
    # all_next: 所有股票的面板数据，选股回测日收益率
    # span: 历史数据为前多少期

    # 记录各期
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)

    for day in range(span, len(all_Next["交易日期"].unique())):

        # print(date_list[day])
        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]

        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]

        '''--------------主成分法进行同类因子合成------------------'''

        # 计算历史每期IC及Rank_IC

        factors1_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors1_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()
        factors1_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors1_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()
        factors2_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors2_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()
        factors2_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors2_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()

        # 计算最优化权重
        V_cov1 = curr[factors1_name].cov()
        weight1_P = np.linalg.inv(V_cov1) @ factors1_P_IC[factors1_name].mean()
        weight1_S = np.linalg.inv(V_cov1) @ factors1_S_IC[factors1_name].mean()

        V_cov2 = curr[factors2_name].cov()
        weight2_P = np.linalg.inv(V_cov2) @ factors2_P_IC[factors2_name].mean()
        weight2_S = np.linalg.inv(V_cov2) @ factors2_S_IC[factors2_name].mean()

        # 记录加权因子得分
        split_com["因子1最大化P_IC加权"] = np.dot(curr[factors1_name].values, weight1_P)
        split_com["因子1最大化S_IC加权"] = np.dot(curr[factors1_name].values, weight1_S)
        split_com[["因子1最大化P_IC加权", "因子1最大化S_IC加权"]] = data_processor.truncate(
            split_com[["因子1最大化P_IC加权", "因子1最大化S_IC加权"]])
        split_com[["因子1最大化P_IC加权", "因子1最大化S_IC加权"]] = data_processor.standardize(
            split_com[["因子1最大化P_IC加权", "因子1最大化S_IC加权"]])

        split_com["因子2最大化P_IC加权"] = np.dot(curr[factors2_name].values, weight2_P)
        split_com["因子2最大化S_IC加权"] = np.dot(curr[factors2_name].values, weight2_S)
        split_com[["因子2最大化P_IC加权", "因子2最大化S_IC加权"]] = data_processor.truncate(
            split_com[["因子2最大化P_IC加权", "因子2最大化S_IC加权"]])
        split_com[["因子2最大化P_IC加权", "因子2最大化S_IC加权"]] = data_processor.standardize(
            split_com[["因子2最大化P_IC加权", "因子2最大化S_IC加权"]])


        # 等权重计算最大化P_IC因子权重
        split_com["最大化P_IC等权重法综合得分"] = split_com[["因子1最大化P_IC加权", "因子2最大化P_IC加权"]].sum(axis=1)

        # ols计算最大化P_IC加权因子权重
        ols = LinearRegression()
        ols.fit(split_com[["因子1最大化P_IC加权", "因子2最大化P_IC加权"]], split_com["选股回测日收益率"])
        # print(predictions)
        split_com["最大化P_IC法ols法综合得分"] = ols.predict(split_com[["因子1最大化P_IC加权", "因子2最大化P_IC加权"]])


        # 等权重计算最大化P_IC因子权重
        split_com["最大化S_IC等权重法综合得分"] = split_com[["因子1最大化S_IC加权", "因子2最大化S_IC加权"]].sum(axis=1)

        # ols计算最大化S_IC加权因子权重
        ols = LinearRegression()
        ols.fit(split_com[["因子1最大化S_IC加权", "因子2最大化S_IC加权"]], split_com["选股回测日收益率"])
        # print(predictions)
        split_com["最大化S_IC法ols法综合得分"] = ols.predict(split_com[["因子1最大化S_IC加权", "因子2最大化S_IC加权"]])

        '''---------------------------------------------------'''
        com_df = com_df._append(split_com)

    select_factors = ['因子1最大化P_IC加权', '因子2最大化P_IC加权','因子1最大化S_IC加权', '因子2最大化S_IC加权', '最大化P_IC等权重法综合得分', '最大化S_IC等权重法综合得分', '最大化P_IC法ols法综合得分', '最大化S_IC法ols法综合得分']
    result_df = get_statistics(select_factors, com_df)
    return result_df

def get_result_MaxICIR(all_Next, span):
    # all_next: 所有股票的面板数据，选股回测日收益率
    # span: 历史数据为前多少期

    # 记录各期
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)

    for day in range(span, len(all_Next["交易日期"].unique())):
        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]

        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]

        '''--------------主成分法进行同类因子合成------------------'''

        # 计算历史每期IC及Rank_IC, Sgima为因子IC的协方差矩阵
        factors1_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors1_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors1_name]
        Sigma1_P = factors1_P_IC[factors1_name].cov()
        weight1_P = np.linalg.inv(Sigma1_P) @ factors1_P_IC[factors1_name].mean()

        factors1_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors1_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors1_name]
        Sigma1_S = factors1_S_IC[factors1_name].cov()
        weight1_S =  np.linalg.inv(Sigma1_S) @ factors1_S_IC[factors1_name].mean()

        factors2_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors2_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors2_name]
        Sigma2_P = factors2_P_IC[factors2_name].cov()
        weight2_P =  np.linalg.inv(Sigma2_P) @ factors2_P_IC[factors2_name].mean()

        factors2_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors2_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors2_name]
        Sigma2_S = factors2_S_IC[factors2_name].cov()
        weight2_S =  np.linalg.inv(Sigma2_S) @ factors2_S_IC[factors2_name].mean()

        # 记录加权因子得分
        split_com["因子1最大化P_ICIR加权"] = np.dot(curr[factors1_name].values, weight1_P)
        split_com["因子1最大化S_ICIR加权"] = np.dot(curr[factors1_name].values, weight1_S)
        split_com[["因子1最大化P_ICIR加权", "因子1最大化S_ICIR加权"]] = data_processor.truncate(
            split_com[["因子1最大化P_ICIR加权", "因子1最大化S_ICIR加权"]])
        split_com[["因子1最大化P_ICIR加权", "因子1最大化S_ICIR加权"]] = data_processor.standardize(
            split_com[["因子1最大化P_ICIR加权", "因子1最大化S_ICIR加权"]])

        split_com["因子2最大化P_ICIR加权"] = np.dot(curr[factors2_name].values, weight2_P)
        split_com["因子2最大化S_ICIR加权"] = np.dot(curr[factors2_name].values, weight2_S)
        split_com[["因子2最大化P_ICIR加权", "因子2最大化S_ICIR加权"]] = data_processor.truncate(
            split_com[["因子2最大化P_ICIR加权", "因子2最大化S_ICIR加权"]])
        split_com[["因子2最大化P_ICIR加权", "因子2最大化S_ICIR加权"]] = data_processor.standardize(
            split_com[["因子2最大化P_ICIR加权", "因子2最大化S_ICIR加权"]])

        # 等权重计算最大化P_ICIR因子权重
        split_com["最大化P_ICIR等权重法综合得分"] = split_com[["因子1最大化P_ICIR加权", "因子2最大化P_ICIR加权"]].sum(axis=1)

        # ols计算最大化P_ICIR加权因子权重
        ols = LinearRegression()
        ols.fit(split_com[["因子1最大化P_ICIR加权", "因子2最大化P_ICIR加权"]], split_com["选股回测日收益率"])
        # print(predictions)
        split_com["最大化P_ICIR法ols法综合得分"] = ols.predict(split_com[["因子1最大化P_ICIR加权", "因子2最大化P_ICIR加权"]])

        # 等权重计算最大化P_IC因子权重
        split_com["最大化S_ICIR等权重法综合得分"] = split_com[["因子1最大化S_ICIR加权", "因子2最大化S_ICIR加权"]].sum(axis=1)

        # ols计算最大化S_IC加权因子权重
        ols = LinearRegression()
        ols.fit(split_com[["因子1最大化S_ICIR加权", "因子2最大化S_ICIR加权"]], split_com["选股回测日收益率"])
        # print(predictions)
        split_com["最大化S_ICIR法ols法综合得分"] = ols.predict(split_com[["因子1最大化S_ICIR加权", "因子2最大化S_ICIR加权"]])

        '''---------------------------------------------------'''
        com_df = com_df._append(split_com)

    select_factors = ['因子1最大化P_ICIR加权', '因子2最大化P_ICIR加权','因子1最大化S_ICIR加权', '因子2最大化S_ICIR加权', '最大化P_ICIR等权重法综合得分', '最大化S_ICIR等权重法综合得分', '最大化P_ICIR法ols法综合得分', '最大化S_ICIR法ols法综合得分']
    result_df = get_statistics(select_factors, com_df)
    return result_df

def get_result_MeanIC(all_Next, span):
    # all_next: 所有股票的面板数据，选股回测日收益率
    # span: 历史数据为前多少期

    # 记录各期
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)

    for day in range(span, len(all_Next["交易日期"].unique())):
        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]

        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]

        # 计算历史每期IC及Rank_IC, Sgima为因子IC的协方差矩阵
        factors1_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors1_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors1_name]
        weight1_P = factors1_P_IC[factors1_name].mean()



        factors1_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors1_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors1_name]
        weight1_S = factors1_S_IC[factors1_name].mean()


        factors2_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors2_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors2_name]
        weight2_P = factors2_P_IC[factors2_name].mean()

        factors2_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors2_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors2_name]
        weight2_S = factors2_S_IC[factors2_name].mean()

        # 记录加权因子得分
        split_com["因子1平均P_IC加权"] = np.dot(curr[factors1_name].values, weight1_P)
        split_com["因子1平均S_IC加权"] = np.dot(curr[factors1_name].values, weight1_S)
        split_com[["因子1平均P_IC加权", "因子1平均S_IC加权"]] = data_processor.truncate(
            split_com[["因子1平均P_IC加权", "因子1平均S_IC加权"]])
        split_com[["因子1平均P_IC加权", "因子1平均S_IC加权"]] = data_processor.standardize(
            split_com[["因子1平均P_IC加权", "因子1平均S_IC加权"]])

        split_com["因子2平均P_IC加权"] = np.dot(curr[factors2_name].values, weight2_P)
        split_com["因子2平均S_IC加权"] = np.dot(curr[factors2_name].values, weight2_S)
        split_com[["因子2平均P_IC加权", "因子2平均S_IC加权"]] = data_processor.truncate(
            split_com[["因子2平均P_IC加权", "因子2平均S_IC加权"]])
        split_com[["因子2平均P_IC加权", "因子2平均S_IC加权"]] = data_processor.standardize(
            split_com[["因子2平均P_IC加权", "因子2平均S_IC加权"]])

        # 等权重计算平均P_IC因子权重
        split_com["平均P_IC等权重法综合得分"] = split_com[["因子1平均P_IC加权", "因子2平均P_IC加权"]].sum(axis=1)

        # ols计算平均P_IC加权因子权重
        ols = LinearRegression()
        ols.fit(split_com[["因子1平均P_IC加权", "因子2平均P_IC加权"]], split_com["选股回测日收益率"])
        # print(predictions)
        split_com["平均P_IC法ols法综合得分"] = ols.predict(split_com[["因子1平均P_IC加权", "因子2平均P_IC加权"]])

        # 等权重计算最大化P_IC因子权重
        split_com["平均S_IC等权重法综合得分"] = split_com[["因子1平均S_IC加权", "因子2平均S_IC加权"]].sum(axis=1)

        # ols计算最大化S_IC加权因子权重
        ols = LinearRegression()
        ols.fit(split_com[["因子1平均S_IC加权", "因子2平均S_IC加权"]], split_com["选股回测日收益率"])
        # print(predictions)
        split_com["平均S_IC法ols法综合得分"] = ols.predict(split_com[["因子1平均S_IC加权", "因子2平均S_IC加权"]])


        com_df = com_df._append(split_com)

    select_factors = ['因子1平均P_IC加权', '因子2平均P_IC加权','因子1平均S_IC加权', '因子2平均S_IC加权', '平均P_IC等权重法综合得分', '平均S_IC等权重法综合得分', '平均P_IC法ols法综合得分', '平均S_IC法ols法综合得分']
    result_df = get_statistics(select_factors, com_df)
    return result_df

def get_result_HalfIC(all_Next, span, half):
    # all_next: 所有股票的面板数据，选股回测日收益率
    # span: 历史数据为前多少期

    # 记录各期
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)

    for day in range(span, len(all_Next["交易日期"].unique())):
        # 历史数据
        s_df = all_Next[(all_Next["交易日期"] >= date_list[day - span]) & (all_Next["交易日期"] < date_list[day])]

        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]


        seq = []
        for i in range(0, span):
            a = (i + 1 - span - 1) / half
            a = pow(2, a)
            seq.append(a)
        seq_dict = {"期数距离": seq}
        seq_df = pd.DataFrame(data= seq_dict)

        # 计算历史每期IC及Rank_IC, Sgima为因子IC的协方差矩阵
        factors1_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors1_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors1_name]

        #计算半衰加权后历史各期IC
        past_df = pd.DataFrame()
        for factor in factors1_name:
            past_df[factor] = factors1_P_IC[factor].mul(seq_df["期数距离"])
        weight1_P = past_df[factors1_name].mean()



        factors1_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors1_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors1_name]

        #计算半衰加权后历史各期IC
        past_df = pd.DataFrame()
        for factor in factors1_name:
            past_df[factor] = factors1_S_IC[factor].mul(seq_df["期数距离"])
        weight1_S = past_df[factors1_name].mean()


        factors2_P_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors2_name + ["选股回测日收益率"]].corr(method="pearson")["选股回测日收益率"]).reset_index()[factors2_name]
        # 计算半衰加权后历史各期IC
        past_df = pd.DataFrame()
        for factor in factors2_name:
            past_df[factor] = factors2_P_IC[factor].mul(seq_df["期数距离"])
        weight2_P = past_df[factors2_name].mean()

        factors2_S_IC = s_df.groupby("交易日期").apply(
            lambda x: x[factors2_name + ["选股回测日收益率"]].corr(method="spearman")["选股回测日收益率"]).reset_index()[factors2_name]
        #计算半衰加权后历史各期IC
        past_df = pd.DataFrame()
        for factor in factors2_name:
            past_df[factor] = factors2_S_IC[factor].mul(seq_df["期数距离"])
        weight2_S = past_df[factors2_name].mean()

        # 记录加权因子得分
        split_com["因子1半衰P_IC加权"] = np.dot(curr[factors1_name].values, weight1_P)
        split_com["因子1半衰S_IC加权"] = np.dot(curr[factors1_name].values, weight1_S)
        split_com[["因子1半衰P_IC加权", "因子1半衰S_IC加权"]] = data_processor.truncate(
            split_com[["因子1半衰P_IC加权", "因子1半衰S_IC加权"]])
        split_com[["因子1半衰P_IC加权", "因子1半衰S_IC加权"]] = data_processor.standardize(
            split_com[["因子1半衰P_IC加权", "因子1半衰S_IC加权"]])

        split_com["因子2半衰P_IC加权"] = np.dot(curr[factors2_name].values, weight2_P)
        split_com["因子2半衰S_IC加权"] = np.dot(curr[factors2_name].values, weight2_S)
        split_com[["因子2半衰P_IC加权", "因子2半衰S_IC加权"]] = data_processor.truncate(
            split_com[["因子2半衰P_IC加权", "因子2半衰S_IC加权"]])
        split_com[["因子2半衰P_IC加权", "因子2半衰S_IC加权"]] = data_processor.standardize(
            split_com[["因子2半衰P_IC加权", "因子2半衰S_IC加权"]])

        # 等权重计算半衰P_IC因子权重
        split_com["半衰P_IC等权重法综合得分"] = split_com[["因子1半衰P_IC加权", "因子2半衰P_IC加权"]].sum(axis=1)

        # ols计算半衰P_IC加权因子权重
        ols = LinearRegression()
        ols.fit(split_com[["因子1半衰P_IC加权", "因子2半衰P_IC加权"]], split_com["选股回测日收益率"])
        # print(predictions)
        split_com["半衰P_IC法ols法综合得分"] = ols.predict(split_com[["因子1半衰P_IC加权", "因子2半衰P_IC加权"]])

        # 等权重计算最大化P_IC因子权重
        split_com["半衰S_IC等权重法综合得分"] = split_com[["因子1半衰S_IC加权", "因子2半衰S_IC加权"]].sum(axis=1)

        # ols计算最大化S_IC加权因子权重
        ols = LinearRegression()
        ols.fit(split_com[["因子1半衰S_IC加权", "因子2半衰S_IC加权"]], split_com["选股回测日收益率"])
        # print(predictions)
        split_com["半衰S_IC法ols法综合得分"] = ols.predict(split_com[["因子1半衰S_IC加权", "因子2半衰S_IC加权"]])


        com_df = com_df._append(split_com)

    select_factors = ['因子1半衰P_IC加权', '因子2半衰P_IC加权','因子1半衰S_IC加权', '因子2半衰S_IC加权', '半衰P_IC等权重法综合得分', '半衰S_IC等权重法综合得分', '半衰P_IC法ols法综合得分', '半衰S_IC法ols法综合得分']
    result_df = get_statistics(select_factors, com_df)
    return result_df


def get_result_EqualWeight(all_Next):
    # all_next: 所有股票的面板数据，选股回测日收益率
    # span: 历史数据为前多少期

    # 记录各期
    com_df = pd.DataFrame()

    # all_next的时间范围
    date_pd = all_Next["交易日期"].unique()
    date_pd.sort()
    date_list = list(date_pd)
    date_count = len(date_list)
    for day in range(date_count - 130, date_count):


        # 选股当天的指标数据
        curr = all_Next[all_Next["交易日期"] == date_list[day]]

        # 记录当天的选股得分依据
        split_com = pd.DataFrame()
        split_com = pd.DataFrame()
        split_com["交易日期"] = curr["交易日期"]
        split_com["证券代码"] = curr["证券代码"]
        split_com["选股回测日收益率"] = curr["选股回测日收益率"]


        '''--------------等权重法法进行同类因子合成------------------'''

        split_com["因子1等权重合成"] = curr[factors1_name].sum(axis=1) / 3
        split_com["因子2等权重合成"] = curr[factors2_name].sum(axis=1) / 3

        # 等权重计算等权重法因子权重
        split_com["等权重法等权重法综合得分"] = split_com[["因子1等权重合成", "因子2等权重合成"]].sum(axis=1)

        # ols计算等权重法因子权重
        ols = LinearRegression()
        ols.fit(split_com[["因子1等权重合成", "因子2等权重合成"]], split_com["选股回测日收益率"])
        # print(predictions)
        split_com["等权重法ols法综合得分"] = ols.predict(split_com[["因子1等权重合成", "因子2等权重合成"]])
        '''---------------------------------------------------'''
        com_df = com_df._append(split_com)


    select_factors = ['因子1等权重合成', '因子2等权重合成', '等权重法ols法综合得分','等权重法等权重法综合得分']

    result_df = get_statistics(select_factors, com_df)

    return result_df